package com.hex.es.service.impl;

import com.hex.es.annotation.EsBuildParamTypeInfo;
import com.hex.es.service.ParamBuildInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @description: 范围查询参数构建器
 * @author: Hex
 * @date: 2019/11/20 16:29
 */
@Slf4j
@Service
public class ParamBuildRangeImpl implements ParamBuildInterface {

    @Override
    public void paramBuild(Object key, Object value, BoolQueryBuilder boolQueryBuilder, NativeSearchQueryBuilder searchQueryBuilder, EsBuildParamTypeInfo esBuildParamTypeInfo) {
        if (value != null && StringUtils.isNotEmpty(value.toString())) {
            if (Arrays.asList(esBuildParamTypeInfo.fromFieldName()).contains(key.toString())) {
                boolQueryBuilder.must(QueryBuilders.rangeQuery(esBuildParamTypeInfo.rangeQueryField()[getIndex(esBuildParamTypeInfo.fromFieldName(), key)]).from(value).includeLower(true).includeUpper(true));
            }
            if (Arrays.asList(esBuildParamTypeInfo.toFieldName()).contains(key.toString())) {
                boolQueryBuilder.must(QueryBuilders.rangeQuery(esBuildParamTypeInfo.rangeQueryField()[getIndex(esBuildParamTypeInfo.toFieldName(), key)]).to(value).includeLower(true).includeUpper(true));
            }
        }
    }

    private int getIndex(String[] args, Object key) {
        List<String> stringList = Arrays.asList(args);
        for (int i=0;i<stringList.size();i++) {
            if(key.equals(stringList.get(i))){
                return i;
            }
        }
        return 0;
    }
}
